package server.json;

import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import fj.F;

public class FunctionalJSON {

	public static F<List<Map<String,String>>,JSONArray> mapToJSONArray = new F<List<Map<String,String>>,JSONArray>() {

		@Override
		public JSONArray f(List<Map<String, String>> maps) {
			JSONArray jsonArr = new JSONArray();
			for(Map<String,String> m : maps)
			{
				JSONObject obj = new JSONObject();
				for(String key : m.keySet())
				{
					try {
						obj.put(key, m.get(key));
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				jsonArr.put(obj);
			}
			return jsonArr;
		}
		
	};
	
	/**
	 * For queries that return only one row
	 */
	public static F<List<Map<String,String>>,JSONObject> mapToJSONObject = new F<List<Map<String,String>>,JSONObject>() {

		@Override
		public JSONObject f(List<Map<String, String>> arg0) {
			try {
				return (JSONObject)mapToJSONArray.f(arg0).get(0);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
	};
	
	public static F<List<String>,JSONArray> listToJSONArray = new F<List<String>,JSONArray>() {

		@Override
		public JSONArray f(List<String> arg0) {
			JSONArray arr = new JSONArray();
			for(String arg : arg0)
			{
				arr.put(arg);
			}
			return arr;
		}
		
	};
}
